package com.example.test.accountinfoa.message;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.test.accountinfoa.dao.AccountInfoDao;
import com.example.test.accountinfoa.pojo.AccountChangeEvent;
import com.example.test.accountinfoa.service.AccountInfoService;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;


@Component
@RocketMQTransactionListener(txProducerGroup = "producer_group_txmsg_bank1")
public class ProducerTxmsgListener implements RocketMQLocalTransactionListener {
    @Autowired
    private AccountInfoService accountInfoService;

    @Autowired
    private AccountInfoDao accountInfoDao;
    /**
     * 事务消息的回调，就是事务发送成功之后的回调方法
     * @param message
     * @param o
     * @return
     */
    @Transactional
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        try {
            String messageString =new String((byte[]) message.getPayload());
            JSONObject jsonObject=JSONObject.parseObject(messageString);
            String accountChangeEventString =jsonObject.getString("accountChange");
            AccountChangeEvent accountChangeEvent = JSON.parseObject(accountChangeEventString, AccountChangeEvent.class);
            accountInfoService.updateAccountBalance(accountChangeEvent);
            return RocketMQLocalTransactionState.COMMIT;
        }catch (Exception e){
            e.printStackTrace();
           return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        String messageString = new String((byte[]) message.getPayload());
        JSONObject jsonObject = JSONObject.parseObject(messageString);
        String accountChangeEventString = jsonObject.getString("accountChange");
        AccountChangeEvent accountChangeEvent = JSON.parseObject(accountChangeEventString, AccountChangeEvent.class);
        if (accountInfoDao.isExistTx(accountChangeEvent.getTxNo()) > 0) {
            return RocketMQLocalTransactionState.COMMIT;
        } else {
            return RocketMQLocalTransactionState.UNKNOWN;
        }
    }
}
